//    Copyright (C) Kherty.  All rights reserved.
using System;

namespace OpenLS.Spreadsheet
{
    static class CellComparator
    {
        public static int ComparePartialRowRangesUp(PartialRowOrColumnRange r1, PartialRowOrColumnRange r2)
        {
            return CompareCellsUp(r1.Cells[0], r2.Cells[0]);
        }
        public static int ComparePartialRowRangesDown(PartialRowOrColumnRange r1, PartialRowOrColumnRange r2)
        {
            return CompareCellsDown(r1.Cells[0], r2.Cells[0]);
        }
        public static int CompareCellsUp(Cell c1, Cell c2)
        {
            if (c1 == c2)
                return 0;
            return CompareValues(c1.Value, c2.Value);
        }
        public static int CompareValues(object v1, object v2)
        {
            if (v1 is Cell)
                return CompareValues(((Cell)v1).Value, v2);
            if (v2 is Cell)
                return CompareValues(v1, ((Cell)v2).Value);
            if (v1 is int)
                return CompareValues((double)(int)v1, v2);
            if (v2 is int)
                return CompareValues(v1, (double)(int)v2);
            if (v1 == null)
            {
                if (v2 is double)
                    return CompareValues(0.0d, v2);
                v1 = "";
            }
            if (v2 == null)
            {
                if (v1 is double)
                    return CompareValues(v1, 0.0d);
                v2 = "";
            }
/*            if (v1 == null)
            {
                if (v2 == null)
                    return 0;
                return -1;
            }
            if (v2 == null)
                return 1;
  */
            if (v1 is DateTime)
                v1 = DateTimeConverter.DateTimeToDouble((DateTime)v1, DateTimeOrigin.Origin1900);
            if (v2 is DateTime)
                v2 = DateTimeConverter.DateTimeToDouble((DateTime)v2, DateTimeOrigin.Origin1900);
            if (v1 is double)
            {
                if (v2 is double)
                    return ((double)v1).CompareTo((double)v2);
                return -1;
            }
            if (v2 is double)
                return 1;
            if (v1 is string)
            {
                if (v2 is string)
                    return string.Compare((string)v1, (string)v2, true);
                return -1;
            }
            if (v2 is string)
                return 1;
            if (v1 is bool)
            {
                if (v2 is bool)
                    return ((bool)v1).CompareTo((bool)v2);
                return -1;
            }
            if (v2 is bool)
                return 1;
            return 0;
        }
        public static int CompareCellsDown(Cell c1, Cell c2)
        {
            return -CompareCellsUp(c1, c2);
        }
       
    }
}
